#!/usr/bin/env python
# -*- coding: utf-8 -*-
# title       :
# author      : jarry

import sys
import os
import logging
from SceneCheckTool.checkScript.CheckBase import CheckBase

try:
    import maya.cmds as cmds
    import pymel.core as pm
    import jarryLibs.mayakit.MayaUtils as mu

    reload(mu)
except:
    pass

logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)


class AniRubbishNode(CheckBase):
    def __init__(self):
        super(AniRubbishNode, self).__init__()
        self.exculde_nodetype_list = ['transform']
        self.ani_nodeType_list = ['animCurveTA',  'pointConstraint', 'orientConstraint',  'scaleConstraint', 'parentConstraint']

    def get_rubbish_nodes(self):
        # import pymel.core as pm
        # import jarryLibs.mayakit.MayaUtils as mu
        default_rbbish_node_list = [n for n in mu.list_rubbish_node() if not pm.PyNode(n).isReferenced()]
        assemblies_rbbish_node_list = []
        for node in cmds.ls(assemblies=True):
            if cmds.objectType(node) not in self.exculde_nodetype_list:
                node_connect_list = cmds.listConnections(node)
                if not node_connect_list:
                    assemblies_rbbish_node_list.append(node) # cmds.listConnections(node)

        anim_cv_node_list = []
        for node_type in self.ani_nodeType_list:
            for node in cmds.ls(type=node_type):
                node_connect_list = cmds.listConnections(node)
                if not node_connect_list and not pm.PyNode(node).isReferenced():
                    anim_cv_node_list.append(node)
        return default_rbbish_node_list + assemblies_rbbish_node_list + anim_cv_node_list

    def check(self):
        result_proc = self.get_rubbish_nodes()
        if result_proc:
            result_log = u'Error:%s\n' % result_proc
        else:
            result_log = u'Succeed:没有问题\n'

        return result_log

    def fix(self):
        result_proc = self.get_rubbish_nodes()
        if result_proc:
            try:
                for i in result_proc:
                    if cmds.lockNode(i, q=1, l=1) == [True]:
                        try:
                            cmds.lockNode(i, l=0)
                        except:
                            log.warning(u'{}:无法解锁'.format(i))
                            result_proc.remove(i)
                            continue
                cmds.delete(result_proc)
                result_log = u'Succeed:%s已经删除\n' % result_proc
                log.info(result_log)
                return result_log
            except:
                log.error(u'Error:%s没有删除成功\n' % result_proc)
                return u'Error:%s没有删除成功\n' % result_proc
        else:
            result_log = u'Succeed:没有问题\n'
            return result_log